//
//  ShopMainViewController.m
//  BaseFrame
//
//  Created by wingfac on 2017/8/9.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "ShopMainViewController.h"
#import "ShopMainClassifyCell.h"


@interface ShopMainViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIImageView *headerImgView;
Strong NSMutableArray *dataArray; /**<*/

@end

//网络
@implementation ShopMainViewController (NetWorking)

/**
 修改图片
 */
- (void)getmodifyShopAdvertisingMap{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_id":[UserModel sharedInstanced].s_id,
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/modifyShopAdvertisingMap.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImageJPEGRepresentation(self.headerImgView.image, .1);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ShowMessage(responseObject[@"msg"]);
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];

}

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"id":[UserModel sharedInstanced].userId};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/enterTheShopAdvertisingChartInterface.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            for (int i = 0 ; i < [responseObject[@"obj1"] count]; i ++) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"obj1"][i]];
                
                [self.dataArray addObject:dic];
            }
            [self.headerImgView sd_setImageWithURL:[NSURL URLOffsetIPWithString:responseObject[@"obj"]] placeholderImage:[UIImage imageNamed:@"button_mapadd"]];
            if ([responseObject[@"obj"] isEqualToString:@" "]) {
                self.headerImgView.contentMode = UIViewContentModeCenter;
            }else{
                self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
            }
            [self.view addSubview:self.tableView];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getModifyCommodityCategories:(NSDictionary *)dic{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"cc_id":dic[@"cc_id"],
                                 @"cc_name":dic[@"cc_name"]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity_Category/modifyCommodityCategories.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([dic[@"cc_picture"] isKindOfClass:[UIImage class]]) {
            NSData *data = UIImageJPEGRepresentation(dic[@"cc_picture"], .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        if (State(responseObject)) {
//        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
//            [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
//                [self.navigationController popViewControllerAnimated:YES];
//            }];
//        }else{
            ShowMessage(responseObject[@"msg"]);
//        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];

}

@end

@implementation ShopMainViewController
//{
//    BOOL state;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"店铺信息";
    [self getData];
        
    UIButton * rightButton = [[UIButton alloc]init];
    rightButton.size = CGSizeMake(40, 20);
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:DEF_FontSize_11];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 3;
    rightButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    rightButton.layer.borderWidth = 1;
    [rightButton addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置barbutton
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

#pragma mark - Event
- (void)leftBarButtonItemClick{

}

- (void)rightBarButtonItemClick{
    [self.view endEditing:YES];
    [self getmodifyShopAdvertisingMap];
    for (int i = 0; i < self.dataArray.count; i ++) {
        NSDictionary *dic = self.dataArray[i];
        if (![dic[@"cc_name"] isEqualToString:@" "]) {
            [self getModifyCommodityCategories:dic];
        }
    }
}

- (void)tableHeadViewCkick{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        self.headerImgView.image = img;
        self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
//        state = YES;
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

        return kShopMainClassifyCellHeight;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        ShopMainClassifyCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShopMainClassifyCell class])];
        if(!cell){
            cell =  [[ShopMainClassifyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([ShopMainClassifyCell class])];
        }
        cell.model = self.dataArray[indexPath.row];
        cell.setShopImageBlock = ^() {
            [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
                self.dataArray[indexPath.row][@"cc_picture"] = img;
                [self.tableView reloadData];
        }];
            
    };
    cell.getTextFieldString = ^(NSString *str) {
        self.dataArray[indexPath.row][@"cc_name"] = str;
        [self.tableView reloadData];
    };
        return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
}


#pragma mark - set & get


- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableHeaderView = self.headerImgView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];

        
    }
    return _tableView;
}

- (UIImageView *)headerImgView{
    if (!_headerImgView) {
        _headerImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 130/WIDTH_5S_SCALE)];
        _headerImgView.image = [UIImage imageNamed:@"button_mapadd"];
        _headerImgView.backgroundColor = getColor(@"f1f2f6");
        _headerImgView.contentMode = UIViewContentModeCenter;
        _headerImgView.layer.masksToBounds = YES;
        _headerImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tableHeadViewCkick)];
        [_headerImgView addGestureRecognizer:tap];
    }
    return _headerImgView;
}


#pragma mark - data

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = @[
                        ].mutableCopy;
    }
    return _dataArray;
}


@end
